package com.bojiu.lawsearch.lawsearch.controller;

import com.bojiu.lawsearch.lawsearch.model.*;
import com.bojiu.lawsearch.lawsearch.service.BackLawService;
import com.bojiu.lawsearch.lawsearch.util.*;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * @author: afdiao
 * @Date：2020/3/5 23:16
 * @Description: 后台法律法规接口
 */
@Api(description = "后台标题跟条例相关接口，功能已完成！！！")
@RestController
@RequestMapping("backLaw")
@Slf4j
public class BackLawController {

    @Autowired
    BackLawService backLawService;

    @Autowired
    AuthorizationHandle authorizationHandle;

    /**
     * 上传法律规范
     *
     * @param lawBaseInfo
     * @param errors
     * @return
     */
    @ApiOperation(value = "上传条例", notes = "上传标题信息、解析后的excel以及pdf")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = JsonResult.class),
            @ApiResponse(code = 600, message = "未检测到登录，跳转重新登录"),
            @ApiResponse(code = 500, message = "没有权限访问该接口"),
            @ApiResponse(code = 1200, message = "请求字段为空")
    })
    @PostMapping("insert")
    public JsonResult insert(@ApiParam(name = "上传法律的基本信息", value = "上传基本信息字段", required = true) @Valid @RequestBody LawBaseInfo lawBaseInfo, Errors errors, HttpServletRequest request) {
        log.debug("START ============================================,TIME IS :{}", System.currentTimeMillis() / 1000);
        try {
            //先判断权限
            JsonResult authon = authorizationHandle.backHandler(request, Constances.ALL);
            if (!authon.getCode().equals("200")) {
                return authon;
            }

            if (errors.hasErrors()) {
                JsonResult jsonResult = UtilTools.handleNullField(errors);
                return jsonResult;
            }
            if (StringUtils.isEmpty(lawBaseInfo.getPdfFileName())) {
                log.error("上传的pdf不能为空");
                return new JsonResult(ResultCode.NULLFIELD, "上传的pdf不能为空");
            }

            if (StringUtils.isEmpty(lawBaseInfo.getExcelName())) {
                log.error("上传的excel不能为空");
                return new JsonResult(ResultCode.NULLFIELD, "上传的excel不能为空");
            }
            JsonResult jsonResult = backLawService.insertLawBaseInfo(lawBaseInfo);
            return jsonResult;
        } catch (Exception e) {
            log.error("error to insert backLawBaseInfo,error is:{}", e);
            return new JsonResult(ResultCode.FAIL);
        }
    }

    /**
     * 获取大标题的列表
     *
     * @param pageSize
     * @param pageNum
     * @param string
     * @param request
     * @return
     */
    @ApiOperation(value = "标题列表", notes = "上传基本信息的标题列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = LawBaseInfo.class),
            @ApiResponse(code = 600, message = "未检测到登录，跳转重新登录"),
            @ApiResponse(code = 500, message = "没有权限访问该接口")
    })
    @PostMapping("baseinfoList/{pageNum}/{pageSize}")
    public JsonResult getLawLists(@ApiParam(name = "pageNum", value = "页码", required = true) @PathVariable("pageNum") int pageNum, @ApiParam(name = "pageSize", value = "每页个数", required = true) @PathVariable("pageSize") int pageSize, @ApiParam(name = "title", value = "提供标题搜索，可以不传，json格式", required = false) @RequestBody String string, HttpServletRequest request) {
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(string, JsonObject.class);
        String name = jsonObject.has("title") ? jsonObject.get("title").getAsString() : null;
        Page<LawBaseInfo> ruleList = backLawService.getBaseInfoList(name, pageNum, pageSize);
        return new JsonResult(ResultCode.SUCCESS, ruleList);
    }

    /**
     * 更新大标题
     *
     * @param lawBaseInfo
     * @param errors
     * @param id
     * @param request
     * @return
     */
    @ApiOperation(value = "更新标题", notes = "更新标题的基本信息，不包括pdf以及excel")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = JsonResult.class),
            @ApiResponse(code = 600, message = "未检测到登录，跳转重新登录"),
            @ApiResponse(code = 500, message = "没有权限访问该接口")
    })
    @PostMapping("updateBaseInfo/{id}")
    public JsonResult updateBaseInfo(@ApiParam(name = "标题对象", value = "json格式", required = true) @Valid @RequestBody LawBaseInfo lawBaseInfo, Errors errors, @ApiParam(name = "id", value = "需要更新标题的id", required = true) @PathVariable("id") int id, HttpServletRequest request) {
        //先判断权限
        JsonResult authon = authorizationHandle.backHandler(request, Constances.ALL);
        if (!authon.getCode().equals("200")) {
            return authon;
        }
        if (errors.hasErrors()) {
            JsonResult jsonResult = UtilTools.handleNullField(errors);
            return jsonResult;
        }
        backLawService.UpdateBaseInfo(lawBaseInfo, id);
        return new JsonResult(ResultCode.SUCCESS);
    }

    @ApiOperation(value = "删除标题", notes = "根据id删除指定标题")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = JsonResult.class),
            @ApiResponse(code = 600, message = "未检测到登录，跳转重新登录"),
            @ApiResponse(code = 500, message = "没有权限访问该接口")
    })
    @GetMapping("deletebaseinfo/{id}")
    public JsonResult deleteBaseInfo(@ApiParam(name = "id", value = "大标题的id", required = false) @PathVariable("id") int id, HttpServletRequest request) {
        //先判断权限
        JsonResult authon = authorizationHandle.backHandler(request, Constances.ALL);
        if (!authon.getCode().equals("200")) {
            return authon;
        }
        backLawService.deleteBaseInfo(id);
        return new JsonResult(ResultCode.SUCCESS);
    }

    /**
     * 根据大标题id获取相关的法律法规
     *
     * @param titleId
     * @param request
     * @return
     */
    @ApiOperation(value = "获取条例列表", notes = "根据大标题id获取条例列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = Rule.class),
            @ApiResponse(code = 600, message = "未检测到登录，跳转重新登录"),
            @ApiResponse(code = 500, message = "没有权限访问该接口")
    })
    @GetMapping("ruleList/{titleId}")
    public JsonResult getruleList(@ApiParam(name = "titleId", value = "大标题id", required = true) @PathVariable("titleId") int titleId, HttpServletRequest request) {
//        //先判断权限
//        JsonResult authon = authorizationHandle.backHandler(request, Constances.ALL);
//        if (!authon.getCode().equals("200")) {
//            return authon;
//        }
        List<Rule> ruleList = backLawService.getRuleList(titleId);
        return new JsonResult(ResultCode.SUCCESS, ruleList);
    }

    /**
     * 添加条例的标签
     *
     * @param ruleId
     * @param string
     * @param request
     * @return
     */
    @ApiOperation(value = "条例添加标签", notes = "给条例添加自定义标签")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = JsonResult.class),
            @ApiResponse(code = 600, message = "未检测到登录，跳转重新登录"),
            @ApiResponse(code = 500, message = "没有权限访问该接口"),
            @ApiResponse(code = 1800, message = "该标签已存在")
    })
    @PostMapping("addRuleLabel/{ruleId}")
    public JsonResult addRuleLabel(@ApiParam(name = "ruleId", value = "条例id", required = true) @PathVariable("ruleId") int ruleId, @ApiParam(name = "label", value = "自定义标签内容", required = true) @RequestBody String string, HttpServletRequest request) {
        //先判断权限
        JsonResult authon = authorizationHandle.backHandler(request, Constances.ALL);
        if (!authon.getCode().equals("200")) {
            return authon;
        }
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(string, JsonObject.class);
        String label = jsonObject.get("label").getAsString();
        JsonResult jsonResult = backLawService.addRuleLabel(ruleId, label);
        return jsonResult;
    }

    @ApiOperation(value = "获取用户查询的问题", notes = "用户查询的问题")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = JsonResult.class),
            @ApiResponse(code = 600, message = "未检测到登录，跳转重新登录"),
            @ApiResponse(code = 500, message = "没有权限访问该接口"),
    })
    @GetMapping("searchQuestion/{pageNum}/{pageSize}")
    public JsonResult getSearchQuestion(@ApiParam(name = "pageNum", value = "当前页数", required = true) @PathVariable("pageNum") int pageNum, @ApiParam(name = "pageSize", value = "每页条数", required = true) @PathVariable("pageSize") int pageSize, HttpServletRequest request) {
        //先判断权限
        JsonResult authon = authorizationHandle.backHandler(request, Constances.ALL);
        if (!authon.getCode().equals("200")) {
            return authon;
        }
        Page<SearchQuestion> searchQuestion = backLawService.getSearchQuestion(pageNum, pageSize);
        return new JsonResult(ResultCode.SUCCESS, searchQuestion);
    }


    /**
     * 详细条例富文本修改
     *
     * @param ruleId
     * @param string
     * @param request
     * @return
     */
    @ApiOperation(value = "详细条例修改", notes = "用富文本修改条例内容")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = JsonResult.class),
            @ApiResponse(code = 600, message = "未检测到登录，跳转重新登录"),
            @ApiResponse(code = 500, message = "没有权限访问该接口")
    })
    @PostMapping("updateRuleContent/{ruleId}")
    public JsonResult updateRuleContent(@ApiParam(name = "ruleId", value = "条例id", required = true) @PathVariable("ruleId") int ruleId, @ApiParam(name = "content", value = "详细条例内容", required = true) @RequestBody String string, HttpServletRequest request) {
        //先判断权限
        JsonResult authon = authorizationHandle.backHandler(request, Constances.ALL);
        if (!authon.getCode().equals("200")) {
            return authon;
        }
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(string, JsonObject.class);
        String content = jsonObject.get("content").getAsString();
        JsonResult jsonResult = backLawService.updateRuleContent(ruleId, content);
        return jsonResult;
    }



    /**
     * 获取帮助页
     *
     * @return
     */
    @ApiOperation(value = "获取帮助页", notes = "获取帮助页")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = JsonResult.class),
            @ApiResponse(code = 600, message = "未检测到登录，跳转重新登录"),
            @ApiResponse(code = 500, message = "没有权限访问该接口")
    })
    @GetMapping("getHelpPage")
    public JsonResult getHelpPage(HttpServletRequest request) {
        Help result = backLawService.getHelpPage();
        return new JsonResult(ResultCode.SUCCESS, result);
    }



    /**
     * 更新帮助页
     *
     * @return
     */
    @ApiOperation(value = "更新帮助页", notes = "更新帮助页")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = JsonResult.class),
            @ApiResponse(code = 600, message = "未检测到登录，跳转重新登录"),
            @ApiResponse(code = 500, message = "没有权限访问该接口")
    })
    @PostMapping("updateHelpPage")
    public JsonResult updateHelpPage(@ApiParam(name = "content", value = "帮助页详情", required = true) @RequestBody String string, HttpServletRequest request) {
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(string, JsonObject.class);
        String content = jsonObject.get("content").getAsString();
        JsonResult jsonResult = backLawService.updateHelpPage(content);
        return jsonResult;
    }
}
